package com.tzinfo.tzt.util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/11/8.
 */
public class HttpUtils {

    public static String doPostMethod(String url) {
        return doPostMethod(url, null);
    }

    public static String doPostMethod(String url, List<NameValuePair> _pairs) {
        return doPostMethod(url, _pairs, -1, -1);
    }

    public static String doPostMethod(String url, List<NameValuePair> _pairs, int CONNECTION_TIMEOUT, int SO_TIMEOUT) {
        HttpClient client = new DefaultHttpClient();
        if (CONNECTION_TIMEOUT != -1)
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);//连接时间
        if (SO_TIMEOUT != -1)
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);//数据传输时间
        HttpPost post = new HttpPost(url);
        try {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();     //添加请求参数

            if (_pairs != null) {
                pairs.addAll(_pairs);
            }
            post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
            HttpResponse response = client.execute(post);
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = null;
            while ((line = rd.readLine()) != null) {
                return line;
            }
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
